package org.example.controller;

import org.example.entity.Image;
import org.example.repository.ImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;

/**
 * ImageController handles image upload and burn operations.
 * By zhangT
 */
@RestController
@RequestMapping("/images")
public class ImageController {

    private static final String UPLOAD_DIR = "src/main/resources/static/uploads/";

    @Autowired
    private ImageRepository imageRepository;

    /**
     * Show the image upload page.
     */
    @GetMapping("/upload")
    public String uploadPage() {
        return "upload"; // Returns the upload page view
    }

    /**
     * Handle image upload.
     */
    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file, Model model) {
        String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        Path path = Paths.get(UPLOAD_DIR + filename);

        try {
            Files.createDirectories(path.getParent());
            file.transferTo(path);

            // Save file information to database
            Image image = new Image();
            image.setFilename(filename);
            image.setUploadTime(LocalDateTime.now());
            image.setExpirationTime(LocalDateTime.now().plusMinutes(1)); // Set expiration time to 1 minute
            Image savedImage = imageRepository.save(image);

            // Add image URL and ID to model
            model.addAttribute("message", "Image Uploaded Successfully.");
            model.addAttribute("imageUrl", "/uploads/" + filename);
            model.addAttribute("imageId", savedImage.getId());
        } catch (IOException e) {
            model.addAttribute("message", "Failed to upload image: " + e.getMessage());
        }

        return "upload"; // Return upload page view
    }

    /**
     * Burn (delete) the image by ID.
     */
    @PostMapping("/burn/{id}")
    public ResponseEntity<String> burnImage(@PathVariable Long id) {
        Optional<Image> imageOptional = imageRepository.findById(id);
        
        if (imageOptional.isPresent()) {
            Image image = imageOptional.get();
            Path path = Paths.get("src/main/resources/static/uploads/" + image.getFilename());
            try {
                Files.deleteIfExists(path);
                imageRepository.delete(image);
                return ResponseEntity.ok("Image burned successfully.");
            } catch (IOException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                     .body("Failed to burn image: " + e.getMessage());
            }
        }
        
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Image not found.");
    }
}
